/**
 * API 模块统一导出文件
 * 便于在组件中统一引入和使用
 */

// 导入所有 API 模块
import { authAPI } from './auth'
import { usersAPI } from './users'
import { stationsAPI } from './stations'
import { itemsAPI } from './items'
import { ordersAPI } from './orders'
import { analyticsAPI } from './analytics'
import { settingsAPI } from './settings'
import { dashboardAPI } from './dashboard'

// 导入配置
import apiClient, { API_BASE_URL, createMockProxy, mockAPI } from './config'

// 创建支持 mock 的 API 实例
const mockEnabledAuthAPI = createMockProxy(authAPI, mockAPI.auth)
const mockEnabledUsersAPI = createMockProxy(usersAPI, mockAPI.users)
const mockEnabledStationsAPI = createMockProxy(stationsAPI, mockAPI.stations)
const mockEnabledItemsAPI = createMockProxy(itemsAPI, mockAPI.items)
const mockEnabledOrdersAPI = createMockProxy(ordersAPI, mockAPI.orders)
const mockEnabledAnalyticsAPI = createMockProxy(analyticsAPI, mockAPI.analytics)
const mockEnabledSettingsAPI = createMockProxy(settingsAPI, mockAPI.settings)
const mockEnabledDashboardAPI = createMockProxy(dashboardAPI, {})

/**
 * 统一导出所有 API
 */
export {
  // API 配置
  apiClient,
  API_BASE_URL,
  
  // 各模块 API（支持 mock）
  mockEnabledAuthAPI as authAPI,
  mockEnabledUsersAPI as usersAPI,
  mockEnabledStationsAPI as stationsAPI,
  mockEnabledItemsAPI as itemsAPI,
  mockEnabledOrdersAPI as ordersAPI,
  mockEnabledAnalyticsAPI as analyticsAPI,
  mockEnabledSettingsAPI as settingsAPI,
  mockEnabledDashboardAPI as dashboardAPI
}

// 单独导出原始 API（不经过 mock 代理）
export { authAPI as originalAuthAPI } from './auth'
export { usersAPI as originalUsersAPI } from './users'
export { stationsAPI as originalStationsAPI } from './stations'
export { itemsAPI as originalItemsAPI } from './items'
export { ordersAPI as originalOrdersAPI } from './orders'
export { analyticsAPI as originalAnalyticsAPI } from './analytics'
export { settingsAPI as originalSettingsAPI } from './settings'
export { dashboardAPI as originalDashboardAPI } from './dashboard'

/**
 * 默认导出聚合对象，方便使用
 */
export default {
  // API 配置
  client: apiClient,
  baseURL: API_BASE_URL,
  
  // 各模块 API（支持 mock）
  auth: mockEnabledAuthAPI,
  users: mockEnabledUsersAPI,
  stations: mockEnabledStationsAPI,
  items: mockEnabledItemsAPI,
  orders: mockEnabledOrdersAPI,
  analytics: mockEnabledAnalyticsAPI,
  settings: mockEnabledSettingsAPI,
  dashboard: mockEnabledDashboardAPI
}

/**
 * 通用 API 工具函数
 */
export const apiUtils = {
  /**
   * 构建查询参数字符串
   * @param {Object} params - 参数对象
   * @returns {string} 查询字符串
   */
  buildQueryString(params) {
    const searchParams = new URLSearchParams()
    Object.keys(params).forEach(key => {
      if (params[key] !== null && params[key] !== undefined && params[key] !== '') {
        searchParams.append(key, params[key])
      }
    })
    return searchParams.toString()
  },

  /**
   * 格式化日期为 API 需要的格式
   * @param {Date|string} date - 日期
   * @returns {string} 格式化后的日期字符串
   */
  formatDate(date) {
    if (!date) return ''
    const d = new Date(date)
    return d.toISOString().split('T')[0]
  },

  /**
   * 格式化日期时间为 API 需要的格式
   * @param {Date|string} datetime - 日期时间
   * @returns {string} 格式化后的日期时间字符串
   */
  formatDateTime(datetime) {
    if (!datetime) return ''
    const d = new Date(datetime)
    return d.toISOString()
  },

  /**
   * 处理文件下载
   * @param {Blob} blob - 文件 blob
   * @param {string} filename - 文件名
   */
  downloadFile(blob, filename) {
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = filename
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
  },

  /**
   * 处理 API 错误
   * @param {Error} error - 错误对象
   * @returns {string} 错误消息
   */
  handleError(error) {
    if (error.response) {
      // 服务器响应错误
      return error.response.data?.message || '服务器错误'
    } else if (error.request) {
      // 网络错误
      return '网络连接失败，请检查网络设置'
    } else {
      // 其他错误
      return error.message || '未知错误'
    }
  },

  /**
   * 重试机制
   * @param {Function} apiCall - API 调用函数
   * @param {number} maxRetries - 最大重试次数
   * @param {number} delay - 重试延迟（毫秒）
   * @returns {Promise} API 调用结果
   */
  async retry(apiCall, maxRetries = 3, delay = 1000) {
    let lastError
    
    for (let i = 0; i <= maxRetries; i++) {
      try {
        return await apiCall()
      } catch (error) {
        lastError = error
        if (i < maxRetries) {
          await new Promise(resolve => setTimeout(resolve, delay * Math.pow(2, i)))
        }
      }
    }
    
    throw lastError
  }
}
